package me.jollyfly.jshop.item.server.service.impl

import me.jollyfly.jshop.item.client.model.ItemCategoryDO
import me.jollyfly.jshop.item.server.dao.ItemCatDAO
import me.jollyfly.jshop.item.server.service.ItemCatService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.stream.Collectors

@Service
open class ItemCatServiceImpl : ItemCatService {


    @Autowired
    private var itemCatDAO: ItemCatDAO? = null

    @Autowired
    private var redisTemplate: RedisTemplate<String, Any>? = null


    @Transactional(readOnly = true, rollbackFor = [(Exception::class)])
    override fun listCategory(): List<ItemCategoryDO> {

        try {
            @Suppress("UNCHECKED_CAST")
            return redisTemplate!!.opsForValue()[REDIS_INDEX_MENU_KEY] as List<ItemCategoryDO>
        } catch (e: Exception) {
            logger.warn("从缓存加载菜单信息异常", e.message)
        }

        val itemCatMap = itemCatDAO!!.selectAll().associateBy { it.id }
        itemCatMap.forEach { _, u ->
            if (u.asParent!!) {
                u.children!!.addAll(itemCatMap.filterValues { it.parentId == u.id }.values)
                u.children!!.sortBy { it.sortOrder }
            }
        }
        val menu = itemCatMap.values.stream().collect(Collectors.toList()).filter { it.parentId == 0L }
        menu.sortedBy { it.sortOrder }
        logger.info("load menu form database success")
        logger.debug("加载menu完成，menu：{}", menu)
        try {
            this.redisTemplate!!.opsForValue().setIfAbsent(REDIS_INDEX_MENU_KEY, menu)
        } catch (e: Exception) {
            logger.warn("将菜单存到缓存失败", e.message)
        }
        return menu
    }


    override fun listCatSelector(): List<ItemCategoryDO> {
        val itemCategory = ItemCategoryDO()
        itemCategory.asParent = false
        itemCategory.status = 1
        return this.itemCatDAO!!.select(itemCategory)
    }


    companion object {
        private val logger: Logger = LoggerFactory.getLogger(ItemCatServiceImpl::class.java)

        private const val REDIS_INDEX_MENU_KEY = "REDIS_INDEX_MENU_KEY"

    }
}

